package com.znjc.device.modbus.rtu.slave.util;

import com.intelligt.modbus.jlibmodbus.data.DataHolder;
import com.intelligt.modbus.jlibmodbus.exception.IllegalDataAddressException;
import com.intelligt.modbus.jlibmodbus.exception.IllegalDataValueException;
import com.znjc.device.modbus.rtu.slave.listener.EventListeners;

import java.util.ArrayList;
import java.util.List;

public class MyDataHolder extends DataHolder {
    final List<EventListeners> eventListenerList = new ArrayList<>();
    public void addEventListener(EventListeners eventListener){
        eventListenerList.add(eventListener);
    }
    public boolean removeEventListener(EventListeners eventListener){
        return eventListenerList.remove(eventListener);
    }
    @Override
    public int readHoldingRegister(int offset) throws IllegalDataAddressException {
        for (EventListeners e : eventListenerList){
            e.readHoldingRegister(offset);
        }
        return super.readHoldingRegister(offset);
    }
    @Override
    public int[] readHoldingRegisterRange(int offset, int quantity) throws IllegalDataAddressException {
        for (EventListeners e : eventListenerList){
            e.readHoldingRegisterRange(offset, quantity);
        }
        return super.readHoldingRegisterRange(offset, quantity);
    }
    @Override
    public void writeHoldingRegister(int offset, int value) throws IllegalDataAddressException, IllegalDataValueException {
        for (EventListeners e : eventListenerList){
            e.writeHoldingRegister(offset, value);
        }
        super.writeHoldingRegister(offset, value);
    }
    @Override
    public void writeHoldingRegisterRange(int offset, int[] range) throws IllegalDataAddressException, IllegalDataValueException {
        for (EventListeners e : eventListenerList){
            e.writeHoldingRegisterRange(offset, range);
        }
        super.writeHoldingRegisterRange(offset, range);
    }
}
